<?php 
namespace app\authorization\model;
use think\Model;
use think\Db;
use think\Cache;
use app\authorization\model\RbacMenuModel;
use app\authorization\libs\InterfaceSignatureVerification as ISV;
use app\common\lib\AccessAuthorization as AAZ;

/**
 * 
 */
class ApiUserModel extends Model
{
	public $type = '';
	/**
	 * 验证用户信息
	 */
	public function checkInput( $proof )
	{
		//检查用户是否存在 SELECT  FROM `cmf_user` WHERE 1
		//$user = Db('user')->where( 'md5(CONCAT(user_login,user_pass))' , $proof['uid'] )->where( 'user_type' , 1 )->field('id,user_login,user_status')->find( );
		$user = Db::query( 'SELECT id,user_login,user_status,user_pass FROM cmf_user WHERE  `user_type`=1 AND md5(CONCAT(user_login,user_pass))="'.$proof['uid'].'"' );
		
		if( !isset( $user[0] ) || empty( $user[0] ) ){
			return [ 'status' => false , 'message'=>'用户不存在,请检查输入' , 'code' => 30001 ] ;
		}
		$user = $user[0];
		if( $user[ 'user_status' ] != 1 ){
			return [ 'status' => false , 'message'=>'用户被限制登录' , 'code' => 300021 ] ;
		}
		$userInfo = Db::view( 'user_attach' , '*' )
					->view( 'role' , 'id as role_id , status as role_status' , 'role.id=user_attach.role_id' )
					->view( 'company' , 'id as c_id, status as c_status , active,aid as appid , period , create_time' , 'company.id=user_attach.company_id' )
					->where( 'user_id', $user['id'] )->find();

		//验证是否是最高角色的用户
		$heighestRole = AAZ::getHighestRoleInfo( $user['id'] );
		if( $heighestRole[ 'id' ] != $userInfo [ 'role_id' ] ){
			return [ 'status' => false , 'message'=>'非法操作被拒绝' , 'code' => 20006 ] ;
		}

		$appid = md5(md5($userInfo['c_id'].$userInfo['create_time']));
		$k = md5($userInfo['c_id'].$userInfo['create_time']) ;
		$appsecret = md5(md5($userInfo['c_id'].$appid.$k.$userInfo['create_time']));;
		
		$key = $proof [ 'key' ];

		if( $appid != $proof [ 'appid' ] ){
			return [ 'status' => false , 'message'=>'无效的appid' , 'code' => 20004 ] ;
		} 

		if( false === user_verify( $key , $appsecret , $user[ 'user_login' ] ) ){
			return [ 'status' => false , 'message'=>'无效的key' , 'code' => 20005 ] ;
		}

		if( $userInfo [ 'role_status' ] != 1 ){
			return [ 'status' => false , 'message'=>'用户被限制登录' , 'code' => 300022 ] ;
		}

		if( $userInfo [ 'c_status' ] == 0  ){
			return [ 'status' => false , 'message'=>'用户被限制登录' , 'code' => 300023 ] ;
		}else if( $userInfo [ 'c_status' ] ==  2 ){
			return [ 'status' => false , 'message'=>'账号审核中,请等待...' , 'code' => 30003 ] ;
		}else if( $userInfo [ 'c_status' ] ==  3 ){
			return [ 'status' => false , 'message'=>'账号未通过审核,拒绝登录' , 'code' => 30004 ] ;
		}else if( $userInfo [ 'period' ] < time() ){
			return [ 'status' => false , 'message'=>'账号已过期,拒绝登录' , 'code' => 30005 ] ;
		}else if( $userInfo [ 'active' ] != 1 && $this->type == 'scjh' ){
			return [ 'status' => false , 'message'=>'账号未激活,请激活' , 'code' => 30006 ] ;
		}
		$userInfo [ 'uesr_name' ] = $user[ 'user_login' ];
		$userInfo [ 'user_pass' ] = $user[ 'user_pass' ];
		return $userInfo;
	}

	/**
	 * 生成token
	 */
	public function createToken( $userId , $userPass )
	{
		$token = ISV::createToken( $userId , $userPass );
		if( $token === false ){
			return [ 'status' => false , 'message'=>'创建TOKEN时出错' , 'code' => 30007 ] ;
		}
		//限制请求次数 10分钟内限制请求3次token
		if( Cache::has( 'create_token_'.$userId ) ){
			$che = Cache::get( 'create_token_'.$userId );
		}
		if( !Cache::has( 'create_token_'.$userId ) || $che [ 'time' ] <= time() ){
			$che  [ 'time' ] = time() + 600 ;
			$che  [ 'count' ] = 0;
		}
		//在10分钟内
		if( $che [ 'time' ] >= time()  ){
			if( $che [ 'count' ] > 2 ){
				return [ 'status' => false , 'message'=>'请求token次数过于频繁,已被限制请求,10分钟后再操作!' , 'code' => 30009 ] ;
			}
		}
		$che [ 'count' ] += 1;
		$che = Cache::set( 'create_token_'.$userId  , $che , 7200 );
		return $token;
	}

	/**
	 * 验证token信息
	 */
	public function verifyToken( $token )
	{
		$res = ISV::verifyToken($token);
		if( isset( $res ['sub'] ) ){
			$find = Db('user')->where( 'id' , $res['sub'])->where( 'user_pass' , $res['subpwd'] )->find();
			if( empty( $find ) ){
				return [ 'status'=>false ,'message'=>'token已过期' , 'code' => 20016 ];
			}
		}
		return $res;
	}



	///////////////////////////////////////////////////////////////////////////////////////////////////////////////


	/**
	 *新账号激活获取用户信息
	 * 首要条件确保user是管理员
	 */
	public function getUserInfo( $userId )
	{
		try {
			$user = Db::name('user')->where('id',$userId)->field('id,user_type,last_login_time,create_time,user_status,user_login,user_pass,user_nickname,user_email,avatar,last_login_ip,mobile')->find();
			$attach = Db::name('user_attach')->where('user_id',$userId)->find();
			$company = Db::name('company')->where('id',$attach['company_id'])->field('company_name,company_num,parent_id,status,company_type,create_time,versions_type,address,tel,url,remark')->find();
			$company['admin_id'] = $user['id'];
			$company['company_id'] = $attach['company_id'];
			unset($user['id']);
		} catch (\Exception $e) {
			return [ 'status' => false , 'message'=>'异常:'.$e->getMessage() ];
		}
		$data = [
			'user' => $user,
			'company' => $company
		];
		return $data;
	}

	/**
	 * 更新激活状态
	 */
	public function updateActiveStatus( $userId )
	{
		try {
			$attach=Db::name('user_attach')->where( 'user_id' , $userId )->find();
			$active = Db::name( 'company' )->where( 'id' , $attach['company_id'] )->value( 'active' );
			if( $active > 0 ){
				return [ 'status' => false , 'message'=>'账号已激活,请勿非法操作,恶意请求将被永久封号' ];
			}
			Db::name('company')->where('id',$attach['company_id'])->update(['active'=>1,'active_date'=>time()]);
		} catch (\Exception $e) {
			return [ 'status' => false , 'message'=>'异常:'.$e->getMessage() ];
		}
		return [ 'status' => true , 'message'=>'激活成功' ];
	}

	/**
	 * 获取授权菜单
	 */
	public function getMenu( $userId )
	{
		$authorization = new RbacMenuModel();
		//根据用户id获取被授权的列表信息
		try {
			$res = $authorization->getRbacListByUserId( $userId );
		} catch (\Exception $e) {
			return [ 'status' => false , 'message'=>'异常:'.$e->getMessage() , 'code' => 10004 ];
		}
		
		return $res;
	}

	/**
	 * 修改密码
	 */
	public function modifyPwd( $userId , $param )
	{
		$old = base64_decode( $param [ 'old' ] );
		$new = base64_decode( $param [ 'new' ] );

		if( cmf_compare_password( $new , $old ) ){
			return [ 'status' => false , 'message'=>'修改的密码不能和原密码相同' , 'code' => 107 ];
		}
		$user = Db( 'user' )-> where( 'id' , $userId )->where( 'user_pass' , $old )-> find();
		if( empty( $user ) ){
			return [ 'status' => false , 'message'=>'账号或密码错误' , 'code' => 105 ];
		}

		$res = Db('user')->where( 'id' , $userId )->update( [ 'user_pass' => cmf_password( $new ) ] );

		return $res;
	}
}